﻿using System;
using BikeBouncer.BusinessLayer;
using BikeBouncer.BusinessLayer.Entities;
using Devv.Core.Erroo;
using Devv.Core.Utils;

namespace BikeBouncer.Site
{
	public partial class ForgotPassword_aspx : BasePage
	{
		#region Main methods

		protected void Page_Load(Object sender, EventArgs e)
		{
			ValTxtEmail.ValidationExpression = RegexUtil.Email;

			if (!Page.IsCallback)
			{
				LblEmailNotFound.Visible = false;

				PanForm.Visible = false;
				PanFormSent.Visible = false;
				PanRecovered.Visible = false;
				PanNewPassword.Visible = false;
			}
            
			if (!Page.IsPostBack)
			{
				String key = Request.QueryString["q"];

				if (String.IsNullOrEmpty(key))
				{
					Form.DefaultButton = ButSend.UniqueID;
					PanForm.Visible = true;
				}
				else
				{
					CheckKey(key);
				}
			}
		}

		#endregion

		#region Send email

		protected void ButSend_Click(Object sender, EventArgs e)
		{
			GenerateRecoveryKey();
		}

		private void GenerateRecoveryKey()
		{
			try
			{
				User user = new User(DataAccess.User_Get(TxtEmail.Text));

				if (user.Id > 0)
				{
					UserPasswordRecovery rec = new UserPasswordRecovery();

					rec.User.Id = user.Id;
					rec.RecoveryKey = rec.GenerateKey();

					DataAccess.UserPasswordRecovery_Insert(rec);
					MailManager.RecoverPassword(rec);

					LitEmailSent.Text = GetLocalResourceObject("LitEmailSent.Text").ToString().Replace("#EMAIL", user.Email);

					LblEmailNotFound.Visible = false;
					PanFormSent.Visible = true;
				}
				else
				{
					LblEmailNotFound.Visible = true;
					PanForm.Visible = true;
				}
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex, "Error trying to generate a password recovery key.");
				AppendError(ex, "Recovery key:");
			}
		}

		#endregion

		#region Recovery key (back from email)

		private void CheckKey(String key)
		{
			UserPasswordRecovery rec = new UserPasswordRecovery(key);

			if (rec.User == null || rec.User.Id < 1 || rec.DateGenerated < DateTime.Now.AddDays(-2))
			{
				AppendError(GetLocalResourceObject("Error_InvalidKey").ToString());

				PanForm.Visible = true;
			}
			else
			{
				PanRecovered.Visible = true;
			}
		}

		#endregion

		#region Password reset

		protected void ButGenerateNew_Click(Object sender, EventArgs e)
		{
			UserPasswordRecovery rec = new UserPasswordRecovery(Request.QueryString["q"]);

			ResetPassword(new User(rec.User.Id));
		}

		private void ResetPassword(User user)
		{
			try
			{
				user.Password = SecurityUtil.GeneratePassword(6);

				DataAccess.User_UpdatePassword(user);
				DataAccess.UserPasswordRecovery_Delete(user);

				LitNewPassword.Text = user.Password;

				PanConfirmNew.Visible = false;
				PanNewPassword.Visible = true;
				PanRecovered.Visible = true;
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex, "Error trying to generate and save a new user password.");
				AppendError(ex, "Password generation");
			}
		}

		#endregion
	}
}